<template>
    <div class="task">
      <div class="odds c-shadow">
        <p class="col1">
          <span class="searchItem">任务名称 :</span><el-input class="taskName left" v-model="taskName"></el-input>
          <span class="searchItem">导入日期 :</span><j-datePicker v-model="dateStart" :max="maxTime"></j-datePicker> <span class="space-mark"></span> <j-datePicker v-model="dateEnd" :min="dateStart" :max="curTime"></j-datePicker>
        </p>
        <p class="col2">
          <span class="searchItem">导入用户 :</span><el-input class="personName left" v-model="personName"></el-input>
          <span class="searchItem">任务状态 :</span><j-select ref="select" class="select" v-model="selectName" :initItems="stateType" :selectedIndex="selectedIndex"></j-select>
          <span class="buttons">
            <el-button type="primary" class="btn-search" @click="search()"><i class="iconfont icon-search ent-search"></i> 检索</el-button>
            <el-button type="primary" plain class="btn-reset" @click="reset()"><i class="iconfont icon-fuzhi ent-fuzhi"></i> 重置</el-button>
          </span>
        </p>
      </div>
      <div class="list c-shadow">
        <div class="taskTotal">
          <span>共<span style="color:#40a1f3;"> {{taskTotal}} </span>条任务</span>
          <div class="opreation">
            <el-button type="warning" plain class="btn-download" @click="download()">下载模版</el-button>
            <el-button type="success" plain class="btn-newTask" @click="openModal('newTask')">新建任务</el-button>
            <el-button type="primary" plain class="btn-taskMsg" @click="openModal('taskMsg')">任务通知</el-button>
          </div>
        </div>
        <j-dialog class="upSuccess_dialog" ref="upLoadSuccess">
          <p>
            <img src="../../../static/images/uploadSuccess.png"/>
            <span>任务上传成功!</span>
          </p>
          <div class="upLoadTaskOpreation">
            <el-button type="primary" class="btn-run" @click="runTask()">立即执行</el-button>
            <el-button type="reset"  class="btn-later" @click="closeModal('upLoadSuccess')">暂不执行</el-button>
          </div>
        </j-dialog>
        <j-dialog class="newTask_dialog" ref="newTask" :initTitle="initTitle[1]" @closing="closeModal('newTask')">
        <div class="taskNameInput">
          <span class="describe">任务名称</span>
            <el-input v-model="newTaskName" class="newTaskName" placeholder="必填项:文件导入可以自动读取修改"></el-input>
        </div>
        <div class="upLoadAnnexOpreation">
          <p>
            <el-upload :headers="upLoadHeaders" :on-exceed="exceed" :action="uploadAction" :before-upload="beforeAvatarUpload" :on-success="success" :on-change="fileChange" :on-error="error" :limit="1" accept=".xls,.xlsx" :auto-upload="false" name="file" ref="file" :data="{jobname:this.newTaskName}">
              <span class="upLoadAnnex" style="width:50px;">上传附件</span>
            </el-upload>
            <span style="color:#fe5d4d;">(仅支持excel格式)</span>
          </p>
            <el-button type="primary" class="btn-newTask" @click="newTaskSure()">确定</el-button>
        </div>
        </j-dialog>
        <j-dialog class="taskMsg_dialog" ref="taskMsg" :initTitle="initTitle[2]" @closing="closeModal('taskMsg')">
          <div class="msg-col">
            <span>通知方式</span>
            <div>
              <el-radio v-model="radio" label="邮件">邮件</el-radio>
              <el-radio v-model="radio" label="短信" :disabled="true" title="目前仅支持邮件形式">短信</el-radio>
            </div>
          </div>
          <div class="msg-col msgNameInput">
            <span>邮件名称</span>
            <div>
              <textarea name="" id="" v-model="msgName" class="msgName" placeholder="邮件名称可加多个,用';'号隔开"></textarea>
            </div>
          </div>
          <div class="msg-col checkDescribe">
            <span>通知任务类型</span>
            <div>
              <el-checkbox :label="item.label" v-for="(item,index) in checkList" :key="index" @change="checkType(item)" class="checkbox"></el-checkbox>
            </div>
          </div>
          <div class="giveMessageOpreation">
            <el-button type="primary" class="btn-sure" @click="finishMSgSetting()">确定</el-button>
            <el-button type="reset"  class="btn-cancel" @click="closeModal('taskMsg')">取消</el-button>
          </div>
        </j-dialog>
        <table class="table-fixed lists" width="100%" border="0" cellspacing="0" cellpadding="0" v-if="lists&&lists.length>0">
          <thead>
            <th class="th">序号</th>
            <th class="th">任务名称</th>
            <th class="th">企业数量</th>
            <th class="th">导入用户</th>
            <th class="th">导入日期</th>
            <th class="th">任务状态</th>
            <th class="th">操作</th>
          </thead>
          <tr v-for="(list,index) in lists" :key="index">
            <td class="ent-emphasis text-center">{{index+1|sequenceNumber(listParams.pageNum)}}</td>
            <td class="text-center">
              <router-link :to="{path:'/sysManage/taskInfo/taskRun',query:{name:list.taskName,id:list.id}}">
                {{list.taskName}}
              </router-link>
            </td>
            <td class="text-center">{{list.entNewCount || 0}}</td>
            <td class="text-center">{{list.roleId || '--'}}</td>
            <td class="text-center">{{list.createTime | dateFormat}}</td>
            <td class="text-center">{{list.taskStatus || '--'}}</td>
            <td class="text-center">
              <span class="startTask" v-if="list.taskStatus!=='已开始'" :class="{'notSure':list.entNewCount===0}" @click="startTask(list.id)">开始</span>
              <span class="mask"></span>
              <!-- <span class="abort" @click="abort()">暂停</span>
              <span class="continueTask" @click="continueTask()">继续</span> -->
              <span class="deleteTask" v-if="list.taskStatus!=='已开始'" @click="deleteTask(list.id)">删除</span>
            </td>
          </tr>
        </table>
        </div>
      <div class="block paging-wrap fr">
        <el-pagination v-if="taskTotal>listParams.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="listParams.pageNum"
          :page-size="listParams.pageSize"
          layout="prev, pager, next, jumper"
          :total="taskTotal">
        </el-pagination>
      </div>
    </div>
</template>
<script>
import { sysManage as api } from '../../api'
import { jDatePicker, jSelect, jDialog } from "../../components"
export default {
  name: "taskList",
  data() {
    return {
      dateStart: "", // 导入时间范围 开始日期
      dateEnd: "", // 导入时间范围 结束日期
      taskName: "", // 任务名称检索
      personName: "", // 导入用户名称检索
      selectState: "全部", // 任务当前状态
      selectName: "全部",
      selectedIndex: 0,
      stateType: ["全部", "已完成", "未开始", "进行中", "未完成"], // 查询任务状态
      lists: [],
      taskTotal: 0, // 任务总数
      radio: "邮件",
      msgName: "", // 邮件名称
      newTaskName: "",
      initTitle: ["任务上传", "新建任务", "任务通知设置"],
      flag: true,
      listParams: {
        pageNum: 1,
        pageSize: 10
      },
      checkList: [
        { label: "任务完成", isSel: false, flag: "s" },
        { label: "任务失败", isSel: false, flag: "f" }
      ],
      hostUrl:window.api_fhzCount,
      // uploadAction: window.api_fhzCount + "/importEntInfo/importExcel",
      uploadAction: window.api_fhzCount + "/importEntInfo/importExcel",
      taskId:'' // 上传模版后用来保存任务id
    }
  },
  watch: {
    selectName(value) {
      if (value) {
        this.selectState = value
      }
      this.search()
    }
  },
  filters:{
    sequenceNumber(value, pageNum) {
      return (pageNum-1)*10+value
    }
  },
  computed: {
    maxTime() {
      if (new Date().valueOf() - new Date(this.dateEnd).valueOf() > 0) {
        return this.dateEnd
      } else {
        return this.curTime
      }
    },
    curTime() {
      let date = new Date()
      let year = date.getFullYear()
      let month =
        date.getMonth() > 9 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1)
      let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate()
      return year + "-" + month + "-" + day
    },
    upLoadHeaders() {
      return {
        'Authorization':JSON.parse(sessionStorage.getItem("user")).token || ''
      }
    }
  },
  methods: {
    // 上传成功钩子
    success(data) {
      if (data.code===1&&data.msg==='ok') {
        this.taskId = data.data.id
        this.$refs["newTask"].show = false
        this.$refs["file"].clearFiles()
        this.newTaskName = ""
        this.openModal('upLoadSuccess')
        this.search()
      } else {
        this.tips(data.msg, "error")
      }
    },
    // 文件数量超过限制钩子
    exceed(file) {
      console.log(file.length)
    },
    // 上传失败钩子
    error(err, file, fileList) {
      console.log(err)
      this.newTaskName = ''
      file.status==='fail'&&this.tips('上传失败,请重试!', 'error')
    },
    // 添加文件时触发 将任务名称自动替换为上传文件名
    fileChange(file) {
      if (file.status === 'ready') {
        if (this.newTaskName==='') this.newTaskName = file.name.split('.')[0]
      }
    },
    // 上传之前触发
    beforeAvatarUpload(file) {},
    // 按条件检索任务
    search() {
      let params = Object.assign(this.listParams, {
        qStartTime: this.dateStart || '', // 开始时间 + ' 00:00:00'
        qEndTime: this.dateEnd || '', // 结束时间 + ' 00:00:00'
        taskName: this.taskName || '', // 任务名称
        taskStatus: this.selectState || '全部', // 任务当前状态
        username: this.personName || '' // 用户名称
      })
      // console.log(params)
      api.postImportEntBatchList(params).then(rst => {
        this.lists = rst.data.list || []
        this.taskTotal = rst.data.total || 0
      }).catch(err => {
        this.tips(err.msg, 'error')
      })
    },
    // 重置检索条件
    reset() {
      this.taskName = ""
      this.dateStart = ""
      this.dateEnd = ""
      this.personName = ""
      this.$refs["select"].select({
        data: "全部",
        selected: false,
        text: "全部",
        value: "全部"
      })
      this.search()
    },
    // 下载任务模版
    download() {
      let a = document.createElement("a")
      document.body.appendChild(a)
      a.setAttribute("href", this.hostUrl + "/importEntInfo/modelExport")
      a.setAttribute("download", this.hostUrl + "/importEntInfo/modelExport")
      a.click()
      document.body.removeChild(a)
    },
    // 打开弹框
    openModal(type) {
      switch (type) {
        case 'newTask':
          this.$refs["newTask"].show = true
          this.newTaskName = ''
          break
        case 'taskMsg':
          this.$refs["taskMsg"].show = true
          break
        case 'upLoadSuccess':
          this.$refs["upLoadSuccess"].show = true
          break
        default:break
      }
    },
    // 关闭弹框
    closeModal(type) {
      switch (type) {
        case 'newTask':
          this.$refs["file"].clearFiles()
          this.newTaskName = ""
          this.$refs["newTask"].show = false
          break
        case 'taskMsg':
          this.checkList.forEach(item => {
            item.isSel = false
          })
          this.msgName = ""
          this.$refs["taskMsg"].show = false
          break
        case 'upLoadSuccess':
          this.$refs["upLoadSuccess"].show = false
          break
        default:break
      }
    },
    // 新建任务
    newTaskSure() {
      if (this.newTaskName !== "") {
        this.$refs['file'].uploadFiles.length===1?this.$refs["file"].submit():this.tips("请您先上传附件", "error")
      } else {
        this.tips("请您输入任务名称", "error")
      }
    },
    // 开始任务
    startTask(id) {
      let params = { id: id }
      api.postStartJob(params).then(rst => {
        if (rst.code&&rst.code===1) {
          this.search()
        }
      }).catch(err => {
        this.tips(err.msg, 'error')
      })
    },
    // 删除任务
    deleteTask(id) {
      let params = { id: id }
      api.postDeleteImportEntBatch(params).then(rst => {
        // console.log(rst)
        if (rst.code&&rst.code===1) {
          this.search()
        }
      }).catch(err => {
        this.tips(err.msg, 'error')
      })
    },
    // 立即执行任务
    runTask() {
      if (this.lists.filter(item => item.id===this.taskId)[0].entNewCount!==0) {
        this.startTask(this.taskId)
        this.closeModal('upLoadSuccess')
      } else {
        this.tips('当前任务内无企业,请重新上传!', "error")
        this.closeModal('upLoadSuccess')
      }
    },
    // 任务通知设置完成
    finishMSgSetting() {
      let type = []
      this.checkList.forEach(item => {
        if (item.isSel) type.push(item.flag)
      })
      this.$refs["taskMsg"].show = false
    },
    // 获取通知类型
    checkType(value) {
      value.isSel = !value.isSel
    },
    handleSizeChange() {},
    // 换页
    handleCurrentChange() {
      this.search()
    }
  },
  mounted() {
    this.search()
  },
  components: {
    jDatePicker,
    jSelect,
    jDialog
  }
}
</script>
<style lang="scss" scoped>
$width: 350px;
$padding: 15px;
.task {
  width: 100%;
  box-sizing: border-box;
  .odds {
    height: 130px;
    padding: 30px 20px 0 20px;
    color: #999999;
    p {
      height: 34px;
      .searchItem {
        padding-right: $padding;
      }
      .companyName,
      .taskName,
      .personName {
        width: 190px;
        height: 34px;
      }
      .left {
        padding-right: 90px;
      }
      .buttons {
        height: 100%;
        line-height: 100%;
        padding-left: 240px;
        .btn-search,
        .btn-reset {
          width: 113.5px;
          height: 34px;
          line-height: 8px;
        }
        .btn-search + .btn-reset {
          margin-left: 20px;
        }
      }
    }
    .col1 {
      padding-bottom: 15px;
      .space-mark{
        display: inline-block;
        width: 8px;
        height: 2px;
        vertical-align: middle;
        margin: 0 4px 0 8px;
        background-color: rgba(18, 108, 236, 0.5);
      }
    }
    .col2 {
      padding-top: 15px;
    }
  }
  .list {
    /*min-height: 520px;*/
    margin-top: 20px;
    padding: 0 20px 20px 20px;
  }
  .taskTotal {
    width: 100%;
    height: 34px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 30px;
    .btn-download,
    .btn-newTask,
    .btn-taskMsg {
      height: 34px;
      line-height: 8px;
    }
    .btn-download ~ button {
      margin-left: 20px;
    }
  }
  .upSuccess_dialog,
  .newTask_dialog,
  .taskMsg_dialog {
    width: 400px;
  }
  .upSuccess_dialog {
    p {
      height: 87px;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      align-items: center;
      font-weight: bolder;
      color: #b7b7b7;
      span {
        margin-top: 24px;
      }
    }
    .upLoadTaskOpreation {
      width: 100%;
      height: 87px;
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      .btn-run,
      .btn-later {
        width: 98px;
        height: 34px;
        line-height: 8px;
      }
      .btn-run + .btn-later {
        margin-left: 30px;
      }
    }
  }
  .newTask_dialog {
    .taskNameInput {
      .describe {
        padding-right: $padding;
      }
      .newTaskName {
        padding: 18px 0;
      }
    }
    .upLoadAnnexOpreation {
      display: flex;
      flex-direction: column;
      justify-content: center;
      p {
        font-size: 12px;
        display: flex;
        justify-content: space-between;
        .upLoadAnnex {
          color: #3f8ffa;
          cursor: pointer;
          text-decoration: underline;
        }
      }
      .btn-newTask {
        width: 98px;
        height: 34px;
        margin: 0 auto;
        margin-top: 40px;
        line-height: 8px;
      }
    }
  }
  .taskMsg_dialog {
    .msg-col {
      height: 45px;
      span {
        display: block;
        padding-bottom: 5px;
        font-weight: 500;
      }
    }
    .msgNameInput {
      min-height: fit-content;
      padding-top: 20px;
      .msgName {
        height: 34px;
        min-height: 34px;
        display: block;
        resize: vertical;
        padding: 5px 15px;
        line-height: 1.5;
        box-sizing: border-box;
        width: 100%;
        font-size: inherit;
        color: #606266;
        background-color: #fff;
        background-image: none;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
        max-height: 300px;
      }
      .msgName::-webkit-input-placeholder {
        font: inherit;
      }
    }
    .checkDescribe {
      padding-top: 20px;
    }
    .giveMessageOpreation {
      width: 100%;
      margin-top: 24px;
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      .btn-sure,
      .btn-cancel {
        width: 98px;
        height: 34px;
        line-height: 8px;
      }
      .btn-sure + .btn-cancel {
        margin-left: 30px;
      }
    }
  }
  .lists {
    margin-top: 15px;
    border-radius: 3px;
    margin-bottom: 20px;
    .th {
      font-weight: 800;
    }
    .startTask,
    .deleteTask {
      color: #8da6c8;
      cursor: pointer;
    }
    .notSure{
      display: none;
    }
    .notSure + .mask{
      color: #ccc;
      cursor: not-allowed;
    }
    .notSure + .mask::before{
      content: '开始'
    }
    .suspendTask {
      color: #ff9f3c;
      cursor: pointer;
    }
    .continueTask {
      color: #379aff;
      cursor: pointer;
    }
  }
}
</style>




// WEBPACK FOOTER //
// src/view/sysManage/taskList.vue